# coding=utf8
__author__ = 'lijian'
import monitor
from utils import byteUtil
import datetime
import logging
import manager
import event
import os
from protocol import Packet
import ipc

_monitor = monitor.RtuMonitor.GetInstance()


def getExternalTime():
    packet = Packet(ctrl=0x60)
    for i in range(3):
        response = _monitor.send(packet)
        if response:
            data = response.dataRegion
            year = 2000 + data[0]
            month = data[1]
            day = data[2]
            hour = data[3]
            minute = data[4]
            second = data[5]

            now = datetime.datetime(year, month, day, hour, minute, second)
            logging.info("now time is: %s" % now.strftime("%Y-%m-%d %H:%M:%S"))

            cmd='date "%d-%d-%d %d:%d:%d"' % (year,month,day,hour,minute,second)
            print cmd
            os.system(cmd)

            return True

    return False


def queryDate():
    str=ipc.getBottom()
    gbkData = str.decode("UTF8").encode("GBK")
    data=[]
    for c in gbkData:
        data.append(ord(c))

    data.append(0)

    packet = Packet(ctrl=0x61,data=data)
    response = _monitor.send(packet)
    if response:
        data = response.dataRegion

        level = data[0]
        manager.setLevel(level)

        signalValues = data[1:27]
        for point in range(26):
            value = signalValues[point]
            manager.setSignalValue(point, value)

        offset = 27
        for point in range(81):
            value = byteUtil.decodeFloat(data[offset:offset + 4])
            manager.setAnalogValue(point, value)
            offset += 4

        event.checkRtuException()


def ctrlToLevel(level):
    packet = Packet(ctrl=0x62, data=[level])
    response = _monitor.send(packet)
    if response:
        value = response.dataRegion[0]
        return bool(value)
    else:
        return False


def readTimeSheet(month, day, size):
    data = []
    data.append(month)
    data.append(day)
    data.extend(byteUtil.encodeShort(size))

    packet = Packet(ctrl=0x63, data=data)
    response = _monitor.send(packet)
    if response:
        return response.dataRegion
    else:
        return None


def writeTimeSheet(data):
    packet = Packet(ctrl=0x64, data=data)
    response = _monitor.send(packet)
    if response:
        value = response.dataRegion[0]
        return bool(value)
    else:
        return False